package com.ruoyi.transaction.controller;

import com.ruoyi.common.core.web.domain.AjaxResult;

import com.ruoyi.common.entity.TransactionEntity.DTO.SpuSearchDTO;
import com.ruoyi.transaction.service.SpuSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * SPU搜索控制器
 */
@RestController
@RequestMapping("/api/search")
public class SpuSearchController {

    @Autowired
    private SpuSearchService spuSearchService;

    /**
     * 搜索商品
     */
    @GetMapping("/spus")
    public AjaxResult searchSpus(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            List<SpuSearchDTO> results = spuSearchService.searchSpus(keyword, pageNum, pageSize);
            return AjaxResult.success("搜索成功", results);
        } catch (Exception e) {
            return AjaxResult.error("搜索失败: " + e.getMessage());
        }
    }

    /**
     * 获取搜索建议
     */
    @GetMapping("/suggestions")
    public AjaxResult getSearchSuggestions(@RequestParam String keyword) {
        try {
            List<String> suggestions = spuSearchService.getSearchSuggestions(keyword);
            return AjaxResult.success("获取建议成功", suggestions);
        } catch (Exception e) {
            return AjaxResult.error("获取建议失败: " + e.getMessage());
        }
    }

    /**
     * 同步单个SPU到ES
     */
    @PostMapping("/sync/{spuId}")
    public AjaxResult syncSpuToES(@PathVariable Long spuId) {
        try {
            spuSearchService.syncSpuToES(spuId);
            return AjaxResult.success("同步成功");
        } catch (Exception e) {
            return AjaxResult.error("同步失败: " + e.getMessage());
        }
    }

    /**
     * 批量同步SPU到ES
     */
    @PostMapping("/sync/batch")
    public AjaxResult batchSyncSpusToES() {
        try {
            spuSearchService.batchSyncSpusToES();
            return AjaxResult.success("批量同步成功");
        } catch (Exception e) {
            return AjaxResult.error("批量同步失败: " + e.getMessage());
        }
    }

    /**
     * 从ES删除SPU
     */
    @DeleteMapping("/delete/{spuId}")
    public AjaxResult deleteSpuFromES(@PathVariable Long spuId) {
        try {
            spuSearchService.deleteSpuFromES(spuId);
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            return AjaxResult.error("删除失败: " + e.getMessage());
        }
    }

    /**
     * 重建索引
     */
    @PostMapping("/rebuild-index")
    public AjaxResult rebuildIndex() {
        try {
            spuSearchService.rebuildIndex();
            return AjaxResult.success("重建索引成功");
        } catch (Exception e) {
            return AjaxResult.error("重建索引失败: " + e.getMessage());
        }
    }
}